package com.financing.wap.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class RequstUtil {
	
	static Logger logger=Logger.getLogger(RequstUtil.class);
	
	static HttpClient hc = null;
	static PostMethod postmethod = new PostMethod();
	static GetMethod getmethod = new GetMethod();
	static{
// 指定协议名称和默认的端口号
		Protocol myhttps = new Protocol("https",
				new MySecureProtocolSocketFactory(), 443);
		// 注册刚才创建的https 协议对象
		Protocol.registerProtocol("https", myhttps);
		hc = new HttpClient();
		hc.getParams().setParameter(
				HttpClientParams.USE_EXPECT_CONTINUE, Boolean.FALSE);
		
		// 设置超时限制
		hc.getHttpConnectionManager().getParams()
		.setConnectionTimeout(10000);
		hc.getHttpConnectionManager().getParams().setSoTimeout(10000);
		//代理  本地代理 测试  or  匿名代理  隐藏IP
//		hc.getHostConfiguration().setProxy("127.0.0.1", 8000);
	}
	
	public static InputStream doRequestStream(String url) {
		try {
			HttpClient hc = null;
			// 指定协议名称和默认的端口号
			@SuppressWarnings("deprecation")
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			// 注册刚才创建的https 协议对象
			Protocol.registerProtocol("https", myhttps);
			hc = new HttpClient();
			hc.getParams().setParameter(
					HttpClientParams.USE_EXPECT_CONTINUE, Boolean.FALSE);

			// 设置超时限制
			hc.getHttpConnectionManager().getParams()
					.setConnectionTimeout(10000);
			hc.getHttpConnectionManager().getParams().setSoTimeout(10000);
			GetMethod getmethod=new GetMethod(url);
			int stat = hc.executeMethod(getmethod);
			InputStream responseBodyAsStream = getmethod.getResponseBodyAsStream();
			return  responseBodyAsStream ;
		} catch (Exception e) {
			logger.error(" error",e);
		}
		return null;
	}
	
	public static String doRequest(String url) {
		try {
			return IOUtils.toString(doRequestStream(url),"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/***
	 * down wx 图片   单独处理 
	 * @param url
	 * @return
	 */
	public static InputStream doRequestStreamByWxImage(String url) {
		try {
			 HttpClient hc = new HttpClient();
			// 设置超时限制
			hc.getHttpConnectionManager().getParams()
					.setConnectionTimeout(10000);
			hc.getHttpConnectionManager().getParams().setSoTimeout(10000);
			GetMethod getmethod=new GetMethod(url);
//			getmethod.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
//			getmethod.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");
//			if(url.contains("mmbiz.qlogo.cn")){
//				getmethod.setRequestHeader(":authority","mmbiz.qlogo.cn");
//				getmethod.setRequestHeader(":method","GET");
//				getmethod.setRequestHeader(":path",getmethod.getURI().getPathQuery());
//				getmethod.setRequestHeader(":scheme","https");
//				getmethod.setRequestHeader("accept-encoding","gzip, deflate, br");
//				getmethod.setRequestHeader("upgrade-insecure-requests","1");
//			}
			int stat = hc.executeMethod(getmethod);
			InputStream responseBodyAsStream = getmethod.getResponseBodyAsStream();
			return  responseBodyAsStream ;
		} catch (Exception e) {
			logger.error(" down image error："+url,e);
		}
		return null;
	}
	// url params 
	public static String postMethod(String url, Map<String, String> params,Map<String,String> heads)
			throws IOException {
		PostMethod postmethod=new PostMethod(url);
		if (params != null && params.size() > 0) {
			Set<Entry<String, String>> set = params.entrySet();
			NameValuePair[] nvps = new NameValuePair[set.size()];
			int i = 0;
			for (Entry<String, String> entry : params.entrySet()) {
				nvps[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			postmethod.addParameters(nvps);
		}
		
		if(heads!=null&&heads.size()>0){
			for (Entry<String, String> entry :  heads.entrySet()) {
				postmethod.setRequestHeader(entry.getKey(), entry.getValue());
			}
		}

		
		int stat = hc.executeMethod(postmethod);
		System.out.println(stat);
		Header[] logins=postmethod.getResponseHeaders();
		if(stat==302){
			for (int i = 0; i < logins.length; i++) {
				System.out.println(logins[i].getName()+"==="+logins[i].getValue());
				if(logins[i].getName().equals("Location")&&StringUtils.isNotBlank(logins[i].getName())){
					System.out.println(logins[i].getValue());
					postmethod.releaseConnection();
					postMethod(logins[i].getValue(), null,null);
				}
			}
		}
		String str = IOUtils.toString(postmethod.getResponseBodyAsStream(),"UTF-8");
		postmethod.releaseConnection();
		return str;
	}
	public static void main(String[] args) throws Exception {
			FileOutputStream fileOutputStream = new FileOutputStream(new File("D://disk/usr/"+new Random().nextInt(1000)+".jpg"));
			InputStream doRequestStreamByWxImage = doRequestStreamByWxImage("https://mmbiz.qlogo.cn/mmbiz_jpg/bkmtjaLJSibRHu1lLJ8G4IwL9mcx2zEVe9hWTzUzaWB3T2Uvv0YMLnJPdedv7JiaVxod3xIuHmkBVvZbz6AJcNwg/0?wx_fmt=jpeg");
			IOUtils.copy(doRequestStreamByWxImage, fileOutputStream);
	}
}
